import React from 'react';
import {
    Form,
    Input,
    DatePicker,
    Select,
    Cascader,
    Row,
    Col,
    Checkbox,
    Button,
    Modal,
    Table,
    Pagination,
    Radio,
    Icon,
    Collapse,
    Upload,
    message
} from 'antd';
import util from 'util';
import $ from 'jquery';


const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const Panel = Collapse.Panel;

//搜索面板---
@Form.create()
class Search extends React.Component {
    search(e) {
        e.preventDefault();
        console.log('接受到表单值', this.props.form.getFieldsValue());
        this.props.search(this.props.form.getFieldsValue());
    }

    reset(e) {
        e.preventDefault();
        var {resetFields} = this.props.form;
        resetFields();
    }

    render() {
        const {getFieldProps, getFieldValue} = this.props.form;
        var title = getFieldProps("title");
        var content = getFieldProps("content");
        var createdatestart = getFieldProps("createdatestart");
        var createdateend = getFieldProps("createdateend");
        var updatedatestart = getFieldProps("updatedatestart");
        var updatedateend = getFieldProps("updatedateend");
        return (
            <Collapse defaultActiveKey={['1']}>
                <Panel header="查询公告信息" key="1">
                    <Form inline className="ant-advanced-search-form">
                        <Row>
                            <Col span={8}>
                                <FormItem label="公告标题：">
                                    <Input
                                        {...title}
                                    />
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label="发布日期范围：">
                                    <DatePicker {...getFieldProps('createdatestart')} />
                                </FormItem>
                            </Col>
                            <Col span="8">
                                <FormItem>
                                    <span style={{position: "absolute", left: -30}}>至</span>
                                    <DatePicker {...getFieldProps('createdateend')} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span="8">
                                <FormItem label="公告内容：">
                                    <Input
                                        {...content}
                                    />
                                </FormItem>
                            </Col>
                            <Col span="8">
                                <FormItem label="修改日期范围：">
                                    <DatePicker {...getFieldProps('updatedatestart')} />
                                </FormItem>
                            </Col>
                            <Col span="8">
                                <FormItem>
                                    <span style={{position: "absolute", left: -30}}>至</span>
                                    <DatePicker {...getFieldProps('updatedateend')} />
                                </FormItem>
                            </Col>
                        </Row>

                        <Row style={{textAlign: 'center'}}>
                            <Button className="btnMarginRright" type="primary" htmlType="submit"
                                    onClick={this.search.bind(this)}
                            >搜索</Button>
                            <Button htmlType="submit" onClick={this.reset.bind(this)}>重置</Button>
                        </Row>
                    </Form>
                </Panel>
            </Collapse>
        );
    }
}
@Form.create()
class UserForm extends React.Component {
    constructor(props) {
        super(props);
        console.log("this.props.data.filepath--->", this.props.data.filepath);
        this.state = {
            roleChildren: [],
            filename: this.props.data.filename,
            filepath: this.props.data.filepath,
            fileList: [{
                uid: -1,
                name: this.props.data.filename,
                status: 'done',
                url: util.baseUrl + "platform/downloadfile.json?resource_id=" + this.props.data.filepath,
            }]
        };
    }

    componentDidMount() {
        console.log("文件名：", this.props.data.filename);
        //角色下拉选项saaa
        util.httpRequest({
            type: "POSt", url: 'role020204.json', params: {}, success: function (result) {
                console.log("角色:", result);
                var roledict = result.rows,
                    rolelist = [], defaultValues = [];
                for (let i = 0; i < roledict.length; i++) {
                    rolelist.push(<Option key={roledict[i].roleid}>{roledict[i].rolename}</Option>);
                }
                this.setState({
                    roleChildren: rolelist
                });
            }.bind(this)
        });
    }

    // componentWillReceiveProps(nextProps) {
    //     console.log("nextProps",nextProps);
    //     this.setState({
    //         filename: nextProps.data.filename,
    //         filepath: nextProps.data.filepath,
    //         fileList: [{
    //             uid: -1,
    //             name: nextProps.data.filename,
    //             status: 'done',
    //             url: util.baseUrl + "platform/downloadfile.json?resource_id=" + nextProps.data.filepath
    //         }]
    //     });
    // }




    compareDate(rule, value, callback) {
        const {getFieldValue} = this.props.form;
        if (value && getFieldValue('release_date') && value <= getFieldValue('release_date')) {
            callback('失效日期应大于生效日期==！');
        } else {
            callback();
        }
    }

    compareDate2(rule, value, callback) {
        const {getFieldValue} = this.props.form;
        console.log(value, getFieldValue('invalid_date'));
        if (value && getFieldValue('invalid_date') && value >= getFieldValue('invalid_date')) {
            callback('生效日期应小于失效日期！');
        } else {
            callback();
        }
    }

    handleUpload(info) {
        console.log(info);
        //限制文件上传数量---
        let fileList = info.fileList;
        fileList = fileList.slice(-1);
        console.log("限制文件上传数量",fileList);


        if (fileList[0]) {
            if (fileList[0].response) {
                if (typeof(fileList[0].response) == "string") {
                    //如果response是字符串则转为对象
                    fileList[0].response = JSON.parse("{" + fileList[0].response.split("{")[1]);
                }
                fileList[0].url = util.baseUrl + "platform/downloadfile.json?resource_id=" + fileList[0].response.resource_id;
            }
        }
        //fileList.url=null
        this.setState({fileList: fileList});
        if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {

            console.log("done");
            if (info.file.response.ret_code === '0000') {

                message.success(`${info.file.name} 上传成功`);

            } else {
                message.error(`${info.file.name} 上传失败,请重新上传`);
            }
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 上传失败`);
            console.log("error");
        }
    }

    render() {
        const disabledDate=function (current) {
            var date = new Date();
            date.setDate(date.getDate() - 1);
            return current && current.getTime()<date;
        };
        var me = this;
        console.log(me);
        const {getFieldProps, getFieldValue} = this.props.form;
        //console.log(getFieldProps("filename"));
        var title = getFieldProps("title", {
            rules: [
                {required: true, whitespace: true, min: 0, message: '公告标题必须输入!'}
            ]
        });
        var content = getFieldProps("content", {
            rules: [
                {required: true, whitespace: true, min: 0, message: '公告内容必须输入！'}
            ]
        });
        var release_date = getFieldProps("release_date", {
            rules: [
                {type: 'date', required: true, message: '生效日期必须输入！'},
                {
                    validator: this.compareDate2.bind(this)
                }
            ]
        });
        var invalid_date = getFieldProps("invalid_date", {
            rules: [
                {type: 'date', required: true, message: '失效日期必须输入！'},
                {
                    validator: this.compareDate.bind(this)
                }
            ]
        });
        var annfile = {
            name: 'file',
            action: util.upUrl + 'platform/fileupload.json',
            fileList: me.state.fileList,
            headers: {
                authorization: 'authorization-text'
            }, onChange(info) {
                //限制文件上传数量---
                let fileList = info.fileList;
                fileList = fileList.slice(-1);
                console.log("@@@@@@@@@@@@@@",fileList);
                if (fileList[0]) {
                    if (fileList[0].response) {
                        if (typeof(fileList[0].response) == "string") {
                            //如果response是字符串则转为对象
                            fileList[0].response = JSON.parse("{" + fileList[0].response.split("{")[1]);
                        }
                    }
                    fileList[0].url = util.baseUrl + "platform/downloadfile.json?resource_id=" + fileList[0].response.resource_id;
                }
                me.setState({fileList: fileList});
                if (info.file.status !== 'uploading') {

                }
                if (info.file.status === 'done') {
                    message.success(`${info.file.name} 上传成功-----`);
                    console.log(info.file.response.filename, info.file.response.filepath);

                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败。`);
                }
            }
        }

        var roleids = getFieldProps("roleids", {
            rules: [
                {type: 'array', required: true, message: '公告对象必须输入！'}
            ]
        });
        var fileids = getFieldProps("roleids", {
            rules: [
                {type: 'array', required: true, message: '公告对象必须输入！'}
            ]
        });
        const formItemLayout = {
            labelCol: {span: 4},
            wrapperCol: {span: 18}
        };
        return (
            <Form horizontal form={this.props.form}>
                <Row gutter={16}>
                    <Col sm={24}>
                        <FormItem label="公告标题" required {...formItemLayout}
                        >

                            <Input type="text" placeholder="请输入公告标题" {...title}/>

                        </FormItem>
                        <FormItem label="公告内容" required {...formItemLayout}
                        >

                            <Input type="textarea" rows={4} placeholder="请输入公告内容" {...content}/>

                        </FormItem>
                    </Col>
                    <Col sm={24}>
                        <FormItem
                            label="生效日期" required {...formItemLayout}
                        >

                            <DatePicker disabledDate={disabledDate.bind(this)} placeholder="请输入生效日期" {...release_date}/>
                        </FormItem>
                        <FormItem
                            label="失效日期" required {...formItemLayout}
                        >
                            <DatePicker disabledDate={disabledDate.bind(this)} placeholder="请输入失效日期" {...invalid_date}/>
                        </FormItem>
                    </Col>
                    <Col sm={24}>
                        <FormItem
                            label="文件上传"  {...formItemLayout}
                        >
                            <Upload {...annfile}
                                    {...getFieldProps("fileCon", {
                                        onChange: this.handleUpload.bind(this)
                                    })}
                            >
                                <Button type="ghost">
                                    <Icon type="upload"/> 点击上传
                                </Button>
                            </Upload>
                        </FormItem>
                    </Col>
                    <Col sm={24}>
                        <FormItem
                            label="公告对象" {...formItemLayout}
                        >
                            <Select multiple placeholder="请输入公告对象"  {...roleids}>
                                {this.state.roleChildren}
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        );
    }

    login() {
        this.props.form.validateFields((errors, values) => {
            if (!!errors) {
                return;
            }
            console.log(values);
            this.props.login(values);
        })
    }

}

@Form.create()
class AddForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            roleChildren: [],
            list: [],
            fileList: [],
        };

    }

    componentDidMount() {
        //角色下拉选项124sadf2
        util.httpRequest({
            type: "POSt", url: 'role020204.json', params: {}, success: function (result) {
                console.log("角色:", result);
                var roledict = result.rows,
                    rolelist = [];
                for (let i = 0; i < roledict.length; i++) {
                    rolelist.push(<Option key={roledict[i].roleid}>{roledict[i].rolename}</Option>);
                }
                console.log(rolelist);
                this.setState({
                    roleChildren: rolelist
                });
            }.bind(this)
        });

    }


    compareDate(rule, value, callback) {
        const {getFieldValue} = this.props.form;
        console.log("123213-->", value - getFieldValue('release_date'))
        if (value && value <= getFieldValue('release_date')) {
            callback('失效日期应大于生效日期！');
        } else {
            callback();
        }
    }

    compareDate2(rule, value, callback) {
        const {getFieldValue} = this.props.form;
        console.log(value, getFieldValue('invalid_date'));
        if (value && value >= getFieldValue('invalid_date')) {
            callback('生效日期应小于失效日期！');
        } else {
            callback();
        }
    }

    render() {
        const disabledDate=function (current) {
            var date = new Date();
            date.setDate(date.getDate() - 1);
            return current && current.getTime()<date;
        };
        var me = this;
        const {getFieldProps, getFieldValue} = this.props.form;
        var title = getFieldProps("title", {
            rules: [
                {required: true, min: 0, message: '公告标题必须输入!'}
            ]
        });
        var content = getFieldProps("content", {
            rules: [
                {required: true, min: 0, message: '公告内容必须输入！'}
            ]
        });
        var release_date = getFieldProps("release_date", {
            rules: [
                {type: 'date', required: true, message: '生效日期必须输入！'},
                {
                    validator: this.compareDate2.bind(this)
                }
            ]
        });
        var invalid_date = getFieldProps("invalid_date", {
            rules: [
                {type: 'date', required: true, message: '失效日期必须输入！'},
                {
                    validator: this.compareDate.bind(this)
                }
            ]
        });
        var annfile = {
            name: 'file',
            action: util.upUrl + 'platform/fileupload.json',

            headers: {
                authorization: 'authorization-text'
            }, beforeUpload(file) {
                //console.log(file.type);
                //const isJPG = file.type === 'image/jpeg';
                //if (!isJPG) {
                //    message.error('只能上传 JPG 文件哦！');
                //}
                //return isJPG;
            }, onChange(info) {
                //console.log("info--",me.props.isNew)
                //if(me.props.isNew && !me.open) me.open = true;

                //if (info.file.status !== 'uploading') {
                //    console.log("--",info.file, info.fileList);
                //}
                //console.log("info--",info)
                let fileList = info.fileList;
                fileList = fileList.slice(-1);
                if (fileList[0]) {
                    if (typeof(fileList[0].response) == "string") {
                        //如果response是字符串则转为对象
                        fileList[0].response = JSON.parse("{" + fileList[0].response.split("{")[1]);
                    }
                    if (fileList[0].response) fileList[0].url = util.baseUrl + "platform/downloadfile.json?resource_id=" + fileList[0].response.resource_id;
                }
                me.setState({fileList: fileList});

                if (info.file.status === 'done') {
                    console.log("上传完成===", info, info.file.response.file_name, "===", info.file.response.resource_id);

                    me.props.onChange(info.file.response.file_name, info.file.response.resource_id);

                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败。`);
                }
            },
        };
        var roleids = getFieldProps("roleids", {
            rules: [
                {type: 'array', required: true, message: '公告对象必须输入！'}
            ]
        });
        const formItemLayout = {
            labelCol: {span: 4},
            wrapperCol: {span: 18}
        };
        return (
            <Form horizontal form={this.props.form}>
                <Row gutter={16}>
                    <Col sm={24}>
                        <FormItem label="公告标题" required {...formItemLayout}
                        >

                            <Input type="text" placeholder="请输入公告标题" {...title}/>

                        </FormItem>
                        <FormItem label="公告内容" required {...formItemLayout}
                        >

                            <Input type="textarea" rows={4} placeholder="请输入公告内容" {...content}/>

                        </FormItem>
                    </Col>
                    <Col sm={24}>
                        <FormItem
                            label="生效日期" required {...formItemLayout}
                        >

                            <DatePicker disabledDate={disabledDate.bind(this)}placeholder="请输入生效日期" {...release_date} format="yyyy/MM/dd HH:mm:ss" showTime/>
                        </FormItem>
                        <FormItem
                            label="失效日期" required {...formItemLayout}
                        >

                            <DatePicker disabledDate={disabledDate.bind(this)} placeholder="请输入失效日期" {...invalid_date} format="yyyy/MM/dd HH:mm:ss" showTime/>
                        </FormItem>
                    </Col>
                    <Col sm={24}>
                        <FormItem label="文件上传"  {...formItemLayout}>
                            <Upload {...annfile} key={this.props.isNew}>
                                <Button type="ghost">
                                    <Icon type="upload"/> 点击上传
                                </Button>
                            </Upload>
                        </FormItem>

                    </Col>
                    <Col sm={24}>

                        <FormItem
                            label="公告对象" {...formItemLayout}
                        >

                            <Select multiple placeholder="请输入公告对象" {...roleids}>
                                {this.state.roleChildren}
                            </Select>
                        </FormItem>
                    </Col>

                </Row>
            </Form>
        );
    }

    login() {
        this.props.form.validateFields((errors, values) => {
            if (!!errors) {
                return;
            }
            console.log(values);
            this.props.login(values);
        })
    }

}
export {Search, UserForm, AddForm}
